<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Article;
use App\Model\ArticleLike;
use App\Model\ArticleTag;
use App\Model\Comment;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class ArticleController extends AbstractController
{
    #[GetMapping(path: '/sys/article/list')]
    public function list()
    {
        $title = $this->request->input('title', '');
        $categoryId = $this->request->input('categoryId', '');
        $tagId = $this->request->input('tagId', '');
        $status = $this->request->input('status',null);
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $where = [];
        if ($title){
            $where[] = ['title','like', '%'.$title.'%'];
        }
        if ($categoryId){
            $where[] = ['category_id','=',$categoryId];
        }
        if ($tagId){
            $article_id = ArticleTag::query()->where('tag_id', $tagId)->pluck('article_id');
            $where[] = [function ($query) use ($article_id) {
                return $query->whereIn('id', $article_id);
            }];
        }
        if (!is_null($status)){
            $where[] = ['status','=',$status];
        }

        $list = Article::query()
            ->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type', 'is_stick as isStick', 'status', 'quantity', 'create_time as createTime')
            ->when($where,function ($query) use($where){
                return $query->where($where);
            })
            ->with(['tags', 'category', 'user'])->forPage($pageNum, $pageSize)->get();
        foreach ($list as &$article) {
            $article->categoryName = $article->category->name ?? '';
            $article->categoryId = $article->category->id ?? 0;
            $article->commentNum = null;
            $article->likeNum = null;
            unset($article->category); // 可选：移除整个 category 对象
            $article->avatar = $article->user->avatar;
            $article->nickname = $article->user->nickname;
            unset($article->user); // 可选：移除整个 user 对象
        }
        $data['searchCount'] = true;
        $data['current'] = (int)$pageNum;
        $data['size'] = (int)$pageSize;
        $data['total'] = Article::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        $data['records'] = $list;
        return success($data);
    }

    #[GetMapping(path: '/sys/article/detail/{id}')]
    public function detail($id)
    {
        $article = Article::query()->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type as readType', 'is_stick as isStick', 'is_original as isOriginal', 'is_recommend as isRecommend', 'is_carousel as isCarousel', 'original_url as originalUrl', 'status', 'quantity', 'keywords')
            ->where('id', $id)
            ->with(['tags'])
            ->first();
        $article->tagIds = $article->tags->pluck('id');
        return success($article);
    }

    #[PutMapping(path: '/sys/article/update')]
    public function update()
    {
        $data = $this->request->all();
        Article::query()->where('id', $data['id'])->update([
            'title' => $data['title'],
            'category_id' => $data['categoryId'],
            'summary' => $data['summary'],
            'content' => $data['content'],
            'content_md' => $data['contentMd'],
            'cover' => $data['cover'],
            'read_type' => $data['readType'],
            'is_stick' => $data['isStick'],
            'is_original' => $data['isOriginal'],
            'is_recommend' => $data['isRecommend'],
            'is_carousel' => $data['isCarousel'],
            'original_url' => $data['originalUrl'],
            'status' => $data['status'],
            'quantity' => $data['quantity'],
            'keywords' => $data['keywords'],
        ]);
        ArticleTag::query()->where('article_id', $data['id'])->delete();
        foreach ($data['tagIds'] as $tagId) {
            ArticleTag::query()->create([
                'article_id' => $data['id'],
                'tag_id' => $tagId,
            ]);
        }
        return success();
    }

    #[PutMapping(path: '/sys/article/updateStatus')]
    public function updateStatus()
    {
        $id = $this->request->input('id');
        $status = $this->request->input('status');
        Article::query()->where('id', $id)->update([
            'status' => $status,
        ]);
        return success();
    }

    #[DeleteMapping(path: '/sys/article/delete/{ids}')]
    public function delete($ids)
    {
        // return fail(201,'删除失败');
        try {
            $idArr = explode(',', $ids);
            Db::beginTransaction();
            foreach ($idArr as $id) {
                $article = Article::query()->where('id', $id)->first();
                if ($article) {
                    Article::query()->where('id', $id)->delete();
                    ArticleTag::query()->where('article_id', $id)->delete();
                    ArticleLike::query()->where('article_id', $id)->delete();
                    Comment::query()->where('article_id', $id)->delete();
                }
            }
            Db::commit();
            return success();
        } catch (\Throwable $e) {
            Db::rollBack();
            logInfo('delete', $e->getMessage(), 'article');
        }

        return fail(201, '删除失败');
    }

    #[PostMapping(path: '/sys/article/add')]
    public function add()
    {
        try {
            Db::beginTransaction();
            $data = $this->request->all();
            $result = Article::query()->create([
                'user_id' => Context::get('uid'),
                'title' => $data['title'],
                'category_id' => $data['categoryId'],
                'summary' => $data['summary'],
                'content' => $data['content'],
                'content_md' => $data['contentMd'],
                'cover' => $data['cover'],
                'read_type' => $data['readType'],
                'is_stick' => $data['isStick'],
                'is_original' => $data['isOriginal'],
                'is_recommend' => $data['isRecommend'],
                'is_carousel' => $data['isCarousel'],
                'original_url' => $data['originalUrl'],
                'status' => $data['status'],
                'keywords' => $data['keywords'],
                'quantity' => 0,
            ]);
            foreach ($data['tagIds'] as $tagId) {
                ArticleTag::query()->create([
                    'article_id' => $result['id'],
                    'tag_id' => $tagId,
                ]);
            }
            Db::commit();
        }catch (\Throwable $e){
            Db::rollBack();
            logInfo('add',$e->getMessage(),'article');
            return fail(201,'添加失败');
        }

        return success();
    }
}
